<template>
    <div class="layout">
        <el-form ref="formRef" :model="form" label-width="auto" :inline="true" class="searchForm">
            <el-row :gutter="24">
                <el-col
                    v-for="item in props.options"
                    :key="item.key"
                    :span="item.type === 'dateFilter' || item.type === 'dateFilterTwo' ? elrowsize : 6">
                    <el-form-item :label="item.label">
                        <template v-if="item.type === 'dateFilter'">
                            <div class="selectTime_btn">
                                <el-button :class="{ active: item.currentId == 0 }" plain @click="selectTime(0, item)">
                                    昨天
                                </el-button>
                                <el-button :class="{ active: item.currentId == 1 }" plain @click="selectTime(1, item)">
                                    最近7天
                                </el-button>
                                <el-button :class="{ active: item.currentId == 2 }" plain @click="selectTime(2, item)">
                                    最近30天
                                </el-button>
                                <el-button :class="{ active: item.currentId == 3 }" plain @click="selectTime(3, item)">
                                    自定义
                                </el-button>
                                <span v-show="isShow" class="daykiy">
                                    <el-date-picker
                                        v-model="form.times"
                                        type="daterange"
                                        :teleported="false"
                                        :editable="false"
                                        :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                                        :format="item.format || 'YYYY-MM-DD HH:mm:ss'"
                                        :value-format="item.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
                                        range-separator="—"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        :disabled-date="item.disabledDate || disabledDate"
                                        @calendar-change="calendarChange(item, $event)"
                                        @change="handleChange" />
                                </span>
                            </div>
                        </template>
                        <template v-if="item.type === 'dateFilterTwo'">
                            <div class="selectTime_btn">
                                <el-button
                                    :class="{ active: item.currentId == 0 }"
                                    plain
                                    @click="selectTimeTwo(0, item)">
                                    昨天
                                </el-button>
                                <el-button
                                    :class="{ active: item.currentId == 1 }"
                                    plain
                                    @click="selectTimeTwo(1, item)">
                                    WTD
                                </el-button>
                                <el-button
                                    :class="{ active: item.currentId == 2 }"
                                    plain
                                    @click="selectTimeTwo(2, item)">
                                    MTD
                                </el-button>
                                <el-button
                                    :class="{ active: item.currentId == 3 }"
                                    plain
                                    @click="selectTimeTwo(3, item)">
                                    YTD
                                </el-button>
                                <el-button
                                    :class="{ active: item.currentId == 4 }"
                                    plain
                                    @click="selectTimeTwo(4, item)">
                                    自定义
                                </el-button>
                                <span v-show="isShow" class="daykiy">
                                    <el-date-picker
                                        v-model="form.times"
                                        type="daterange"
                                        :teleported="false"
                                        :editable="false"
                                        start-placeholder="开始时间"
                                        :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                                        :format="item.format || 'YYYY-MM-DD HH:mm:ss'"
                                        :value-format="item.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
                                        :disabled-date="item.disabledDate || disabledDate"
                                        end-placeholder="结束时间"
                                        range-separator="—"
                                        @calendar-change="calendarChange(item, $event)"
                                        @visible-change="visibleChange(item, $event)"
                                        @focus="handleFocus"
                                        @change="handleChange" />
                                </span>
                            </div>
                        </template>
                        <el-input
                            v-if="item.type === 'input'"
                            v-model="form[item.key]"
                            :readonly="item.readonly"
                            :disabled="item.disabled"
                            :clearable="item.clearable ?? true"
                            :maxlength="item.maxlength"
                            :minlength="item.minlength"
                            :placeholder="item.placeholder"
                            :prefix-icon="item.prefixIcon"
                            :suffix-icon="item.suffixIcon"
                            :autocomplete="item.autocomplete"
                            :autofocus="item.autofocus"
                            @focus="item.focus"
                            @blur="item.blur"
                            @click="item.click"
                            @input="handleInput(item)"
                            @change="item.change"
                            @clear="item.clear" />
                        <el-select
                            v-if="item.type === 'select'"
                            v-model="form[item.key]"
                            :multiple="item.multiple"
                            :disabled="item.disabled"
                            :value-key="item.valueKey"
                            :clearable="item.clearable ?? true"
                            :collapse-tags="item.collapseTags ?? true"
                            :multiple-limit="item.multipleLimit"
                            :name="item.name"
                            :autocomplete="item.autocomplete"
                            :placeholder="item.placeholder"
                            :filterable="item.filterable"
                            :allow-create="item.allowCreate"
                            :filter-method="item.filterMethod"
                            :reserve-keyword="item.reserveKeyword ?? false"
                            :remote="item.remote"
                            :remote-method="query => handleRemoteMethod(item, query)"
                            :loading="item.loading"
                            :loading-text="item.loadingText"
                            :no-match-text="item.noMatchText"
                            :no-data-text="item.noDataText"
                            :popper-class="item.popperClass"
                            :collapse-tags-tooltip="item.collapseTagsTooltip ?? true"
                            @focus="item.focus"
                            @blur="item.blur"
                            @removeTag="submitForm"
                            @visible-change="handleVisibleChange(item)"
                            @change="handleSelectChange(item)">
                            <el-option
                                v-for="option in item.optionList"
                                :key="option.value"
                                :label="option.label"
                                :value="option.value"
                                :disabled="option.disabled" />
                        </el-select>
                        <el-select
                            v-if="item.type === 'depart'"
                            v-model="form[item.key]"
                            :multiple="item.multiple ?? true"
                            :disabled="item.disabled"
                            :clearable="item.clearable ?? true"
                            :collapse-tags="true"
                            :placeholder="item.placeholder"
                            :popper-class="item.popperClass"
                            @removeTag="handleRemoveTag"
                            @click="handleSelectDepartClick(item)"
                            @clear="handleSelectDepartClear">
                            <el-option
                                v-for="option in item.departList"
                                :key="option.id"
                                :label="option.name"
                                :value="option.id"
                                :disabled="option.disabled" />
                        </el-select>
                        <el-select-v2
                            v-if="item.type == 'selectV2'"
                            v-model="form[item.key]"
                            :style="{ width: item.width }"
                            :multiple="item.multiple"
                            :filterable="item.filterable"
                            :collapse-tags="item.collapseTags"
                            :remote="item.remote"
                            :remote-method="query => handleRemoteMethodV2(item, query)"
                            clearable
                            :options="item.optionList"
                            :loading="item.loading"
                            :placeholder="item.placeholder"
                            @change="handleSelectChange(item)">
                            <template #default="{ item }">
                                <span> {{ item.label }} {{ item.status == 1 ? '（已下架）' : '' }} </span>
                            </template>
                        </el-select-v2>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <!-- 部门人员弹框 -->
        <ZWDepart ref="ZWDepartRef" v-model:show="show" v-bind="departItem" @submit="onDepartSubmit" />
    </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onBeforeMount } from 'vue';
import ZWDepart from '@/components/zw/depart/Depart';
import { getDay, timeSlotChange } from '@/utils/utils';
import { debounce } from 'lodash';
const isShow = ref(false); //自定义显示
const pickDay = ref();
const elrowsize = ref(24);
const props: any = defineProps({
    options: {
        type: Array,
        default: () => []
    },
    impose: {
        type: Number,
        default: 180
    },
    // 选择时间类型,默认 dateFilter
    type: {
        type: String,
        default: 'dateFilter'
    }
});
const emit = defineEmits(['submit', 'update:current-id']);
// 收集的表单数据
const form: any = reactive({
    times: []
});

// 选择最近时间
const selectTime = (val: number, item?: any) => {
    if (item) {
        item.currentId = val;
    }
    form.currentId = val;
    switch (val) {
        case 0:
            elrowsize.value = 18;
            form.times = [getDay(-1), getDay(-1, true)];
            isShow.value = false;
            submitForm();
            break;
        case 1:
            elrowsize.value = 18;
            form.times = [getDay(-6), getDay(0, true)];
            isShow.value = false;
            submitForm();
            break;
        case 2:
            elrowsize.value = 18;
            form.times = [getDay(-29), getDay(0, true)];
            isShow.value = false;
            submitForm();
            break;
        case 3:
            elrowsize.value = 24;
            form.times = [];
            isShow.value = true;
            break;
    }
};
// 统计查询选择最近时间
const selectTimeTwo = (val: number, item?: any) => {
    if (item) {
        item.currentId = val;
    }
    form.currentId = val;
    switch (val) {
        case 0:
            elrowsize.value = 24;
            form.times = [getDay(-1), getDay(-1, true)];
            isShow.value = false;
            submitForm();
            break;
        case 1:
            elrowsize.value = 24;
            form.times = timeSlotChange('本周');
            isShow.value = false;
            submitForm();
            break;
        case 2:
            elrowsize.value = 24;
            form.times = timeSlotChange('本月');
            isShow.value = false;
            submitForm();
            break;
        case 3:
            elrowsize.value = 24;
            form.times = timeSlotChange('本年');
            isShow.value = false;
            submitForm();
            break;
        case 4:
            elrowsize.value = 24;
            form.times = [];
            isShow.value = true;
            break;
    }
};

// 提交查询
const submitForm = () => {
    // 选择员工组件 - 选择部门 - 多选的情况下 删除自定义的key
    const { key: departKey } =
        props.options.find((item: any) => item.type === 'depart' && !item.isMember && item.multiple) || {};
    if (departKey) {
        emit('submit', { ...form, [departKey]: undefined });
    } else {
        emit('submit', { ...form });
    }
};

const handleFocus = () => {
    pickDay.value = null;
};
const disabledDate = (time: any) => {
    if (!pickDay.value) {
        return time.getTime() < Date.now() - 3600 * 1000 * 24 * 183 || time.getTime() > Date.now();
    }
    if (props.impose) {
        const con1 = new Date(pickDay.value).getTime() - props.impose * 24 * 60 * 60 * 1000;
        const con2 = new Date(pickDay.value).getTime() + props.impose * 24 * 60 * 60 * 1000;
        const con3 = time.getTime() < Date.now() - 3600 * 1000 * 24 * 183 || time.getTime() > Date.now();
        return (time < con1 || time > con2) && con3;
    }
    return false;
};
const calendarChange = (e: any, val: Date[]) => {
    if (props.impose) {
        // 如果有传如的自定义事件就使用自定义事件
        if (e.calendarChange) {
            e.calendarChange(val);
        } else {
            const [pointDay] = val;
            pickDay.value = pointDay;
        }
    }
};

/**
 * 打开选择时间弹框时，恢复默认值
 */
const visibleChange = (e: any, val: Date[]) => {
    if (e.visibleChange) {
        e.visibleChange(val);
    }
};

const handleChange = () => {
    submitForm();
};
const handleInput = debounce(item => {
    submitForm();
}, 500);
const handleSelectChange = (item: any) => {
    if (item.change instanceof Function) {
        item.change();
    } else {
        submitForm();
    }
};

const handleVisibleChange = (item: any) => {
    if (typeof item.fetchOptionApi === 'function') {
        if (!item.optionList || !item.optionList.length) {
            item.loading = true;
            item.fetchOptionApi(item.fetchOptionParams)
                .then((res: any) => {
                    item.optionList = res;
                    item.loading = false;
                })
                .catch(() => {
                    item.loading = false;
                });
        }
    }
    item.visibleChange && typeof item.visibleChange === 'function' && item.visibleChange();
};
const handleRemoteMethod = async (item: any, query: any) => {
    if (!query) return;
    item.loading = true;
    try {
        const remoteData = await item.remoteMethod(query, item);
        item.optionList = remoteData;
    } finally {
        item.loading = false;
    }
};
const handleRemoteMethodV2 = async (item: any, query: any) => {
    if (!query) return;
    item.loading = true;
    try {
        const remoteData = await item.remoteMethod(query, item);
        item.optionList = remoteData;
    } finally {
        item.loading = false;
    }
};

const show = ref(false);
const departItem: any = ref({});
const onDepartSubmit = (data: any) => {
    departItem.value.departList = [...data];
    if (!departItem.value.multiple) {
        form[departItem.value.key] = data[0].id;
    } else {
        form[departItem.value.key] = data.map((item: any) => item.id);
        if (!departItem.value.isMember) {
            setMemberSelect(data);
        }
    }
    submitForm();
};
const setMemberSelect = (data: any, isResetDepart = false) => {
    const userKey: any = [];
    const departmentKey: any = [];

    for (const item of data) {
        const isPush = isResetDepart ? form[departItem.value.key].includes(item.id) : true;
        ({
            department: () => isPush && departmentKey.push(item.id),
            user: () => isPush && userKey.push(item.id)
        })[item.type]?.();
    }
    form[departItem.value.userKey] = userKey;
    form[departItem.value.departmentKey] = departmentKey;
};
const handleRemoveTag = () => {
    // 移除标签的情况下如果是多选并且是可以一起选择员工和员工部门的情况下，根据当前选中的重新设置绑定的值
    if (departItem.value.multiple && !departItem.value.isMember) {
        setMemberSelect(departItem.value.departList, true);
    }
    submitForm();
};
const handleSelectDepartClick = (item: any) => {
    show.value = true;
    departItem.value = item;
    // 单选和多选的情况下，分别做不同的判断
    const formDepartData = departItem.value.multiple ? form[item.key] : [form[item.key]];
    departItem.value.selectedMember =
        item.departList?.filter((deItem: any) => {
            if (formDepartData.includes?.(deItem.id)) {
                return true;
            } else {
                deItem.check = false;
                return false;
            }
        }) ?? [];
};
const ZWDepartRef = ref();
const handleSelectDepartClear = () => {
    if (departItem.value.multiple && !departItem.value.isMember) {
        form[departItem.value.userKey].splice(0, form[departItem.value.userKey].length);
        form[departItem.value.departmentKey].splice(0, form[departItem.value.departmentKey].length);
        ZWDepartRef.value.removeAll();
    }
    submitForm();
};
const onLoad = () => {
    let currentId = 0;
    for (const item of props.options) {
        if (item.type === 'dateFilterTwo') {
            item.currentId = item.currentId ?? 0;
            currentId = item.currentId;
        } else if (item.type === 'dateFilter') {
            item.currentId = item.currentId ?? 1;
            currentId = item.currentId;
        } else if (item.type === 'depart') {
            item.multiple = item.multiple ?? true; // 默认多选
            item.isMember = item.isMember ?? true; // 默认只选择员工
            if (!item.multiple) {
                form[item.key] = item.value;
            } else if (item.isMember) {
                form[item.key] = item.value;
            } else {
                form[item.userKey] = [];
                form[item.departmentKey] = [];
                item.key = item.key || 'userAndDepartment';
                form[item.key] = [];
            }
        } else {
            form[item.key] = item.value;
        }
    }
    if (props.type == 'dateFilter') {
        selectTime(currentId);
    } else if (props.type == 'dateFilterTwo') {
        selectTimeTwo(currentId);
    }
};
onBeforeMount(() => {
    onLoad();
});

defineExpose({
    onLoad
});
</script>
<style lang="scss" scoped>
.layout {
    margin-top: 16px;
    width: 100%;

    .top {
        display: flex;

        &_btn {
            padding: 10px 21px;
            background: #fff;
            border: 1px solid #ff6b00;
            font-size: 16px;
            color: #ff6b00;
            line-height: 16px;
            cursor: pointer;
        }

        .active {
            background: #ff6b00;
            color: #ffff;
        }
    }

    // padding: 0 20px 0 0;
    position: relative;

    // height: 136px;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .searchForm {
        background: #fff;
        position: relative;
        border: 1px solid #eaeaea;
        padding: 20px 20px 0;

        .form_item_input {
            .el-input__inner {
                width: 100px;
            }
        }

        .filter_time {
            margin-left: 15px;
            display: inline-flex;

            .text-center {
                margin: 0 5px;
                color: #969696;
            }

            .picker_time {
                :deep .el-input__prefix {
                    display: none;
                }

                :deep .el-input__inner {
                    width: 150px;
                    box-sizing: border-box;
                    padding: 0 0 0 12px;
                }
            }
        }

        .selectTime_btn {
            display: flex;
            align-items: center;

            .daykiy {
                margin-left: 15px;
                display: flex;
            }

            &_item {
                padding: 0 18px;
                margin-right: 16px;
                background: #fff;
                border-radius: 4px;
                border: 1px solid #eaeaea;
                cursor: pointer;
            }

            .active {
                border: 1px solid #ff6b00;
                color: #ff6b00;
            }
        }

        .search_btn {
            position: absolute;
            top: 5px;
            right: 0;
        }
    }

    .text {
        font-size: 14px;
        color: #848484;
        line-height: 14px;
        text-align: right;
        margin-bottom: 10px;
    }

    .search-btn {
        float: right;
    }
}

:deep(.el-form--inline .el-form-item) {
    width: 100%;
}

:deep(.el-select) {
    width: 100%;
}
</style>
